package com.jy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jy.common.enums.ResponseWrapper;
import com.jy.common.model.user.param.SendMessageTo;
import com.jy.common.tool.ToolForDateTime;
import com.jy.entity.ChatMessages;
import com.jy.entity.User;
import com.jy.mapper.ChatMessagesMapper;
import com.jy.mapper.UserMapper;
import com.jy.service.ChatMessagesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 存储聊天过程中的消息内容 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2024-11-18
 */
@Service
public class ChatMessagesServiceImpl extends ServiceImpl<ChatMessagesMapper, ChatMessages> implements ChatMessagesService {

    private final ChatMessagesMapper chatMessagesMapper;
    private final UserMapper userMapper;


    public ChatMessagesServiceImpl(ChatMessagesMapper chatMessagesMapper, UserMapper userMapper) {
        this.chatMessagesMapper = chatMessagesMapper;

        this.userMapper = userMapper;
    }

    @Override
    public ResponseWrapper getAllUserMessageList(Integer LoginUserAid) {
        // 最终返回结果
        ArrayList<HashMap<String, Object>> result = new ArrayList<>();

        List<ChatMessages> chatMessages = chatMessagesMapper.selectList(new LambdaQueryWrapper<ChatMessages>()
                .eq(ChatMessages::getReceiverId, LoginUserAid)
        );
        Set<Long> sendUserAidSet = new HashSet<>();
        ArrayList<ChatMessages> fillterChatMessages = new ArrayList<>();
        if(chatMessages.size() > 0){
            for (ChatMessages chatMessage : chatMessages) {
                if (!sendUserAidSet.contains(chatMessage.getSenderId())){
                    sendUserAidSet.add(chatMessage.getSenderId());
                    fillterChatMessages.add(chatMessage);
                }
            }
        }
        System.out.println("过滤后的列表：" + fillterChatMessages);
        for (ChatMessages fillterChatMessage : fillterChatMessages) {
            HashMap<String, Object> chatObj = new HashMap<>();
            User user = userMapper.selectById(fillterChatMessage.getSenderId());
            chatObj.put("userAid",fillterChatMessage.getSenderId());
            chatObj.put("avatar",user.getAvatar());
            chatObj.put("pName",user.getName());
            List<ChatMessages> chatMessages1 = chatMessagesMapper.selectList(new LambdaQueryWrapper<ChatMessages>()
                    .eq(ChatMessages::getSenderId, fillterChatMessage.getSenderId())
                    .eq(ChatMessages::getReceiverId, LoginUserAid)
                    .orderByDesc(ChatMessages::getCreateTime)
                    .last("limit 1")
            );
            ChatMessages chatMessages2 = chatMessages1.get(0);
            if(chatMessages2.getMessageType().equals(0)){
                // 文字
                chatObj.put("briefMessage",chatMessages2.getMessageContent());
            }else if (chatMessages2.getMessageType().equals(1)){
                // 语音
                chatObj.put("briefMessage","对方发送了一条语音");
            }else if (chatMessages2.getMessageType().equals(2)){
                // 图片
                chatObj.put("briefMessage","对方发送了一张图片");
            }else if (chatMessages2.getMessageType().equals(3)){
                // 视频
                chatObj.put("briefMessage","对方发送了一个视频");
            }else if(chatMessages2.getMessageType().equals(4)){
                // 位置
                chatObj.put("briefMessage","对方发送了位置");
            }
            chatObj.put("messageTime", ToolForDateTime.formatDateTime(chatMessages2.getCreateTime()));
            chatObj.put("isRead", chatMessages2.getIsRead());
            List<ChatMessages> chatMessages3 = chatMessagesMapper.selectList(new LambdaQueryWrapper<ChatMessages>()
                    .eq(ChatMessages::getSenderId, fillterChatMessage.getSenderId())
                    .eq(ChatMessages::getReceiverId, LoginUserAid)
                    .eq(ChatMessages::getIsRead,false)
            );
            chatObj.put("unReadMessageNum",chatMessages3.size());
            chatObj.put("isShowRedDot",chatMessages3.size() > 0);
            result.add(chatObj);
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper getMessages(Integer userAidByToken, Integer userAid) {

        // 返回结果
        HashMap<String, Object> result = new HashMap<>();

        List<ChatMessages> chatMessages = chatMessagesMapper.selectList(new LambdaQueryWrapper<ChatMessages>()
                .eq(ChatMessages::getSenderId, userAid)
                .eq(ChatMessages::getReceiverId, userAidByToken)
                .or()
                .eq(ChatMessages::getSenderId, userAidByToken)
                .eq(ChatMessages::getReceiverId, userAid)
        );
        System.out.println("消息：" + chatMessages);
        ArrayList<HashMap<String, Object>> hashMaps = new ArrayList<>();
        for (ChatMessages chatMessage : chatMessages) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("messageAid",chatMessage.getAid());
            map.put("content",chatMessage.getMessageContent());
//            System.out.println("发送者：", );
            map.put("isMe",chatMessage.getSenderId().equals(userAidByToken.longValue()));
            map.put("time",ToolForDateTime.LocalDateTimeToString(chatMessage.getCreateTime()));
            Integer messageType = chatMessage.getMessageType();
            if (messageType.equals(0)){
                map.put("type","text");
            }else if(messageType.equals(1)){
                map.put("type","image");
            }else if(messageType.equals(2)){
                map.put("type","video");
            }else if(messageType.equals(3)){
                map.put("type","audio");
            }else if(messageType.equals(4)){
                map.put("type","postion");
            }
            hashMaps.add(map);
        }
        result.put("messages",hashMaps);
        User user = userMapper.selectById(userAid);
        result.put("userName",user.getName());
        result.put("userAvatar",user.getAvatar());
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper sendMessageTo(Integer userAidByToken, SendMessageTo param) {

        int insert = chatMessagesMapper.insert(new ChatMessages() {{
            setSenderId(userAidByToken.longValue());
            setReceiverId(param.getUserAid().longValue());
            setMessageContent(param.getContent());
            setMessageType(0);
            setIsRead(false);
            setChatType("朋友");
            setProductId(0);
        }});
        if (insert > 0){
            return ResponseWrapper.markSuccess();
        }else {
            return ResponseWrapper.markError();
        }
    }
}
